#bin/sh

#----------------------------------------------
# 前后端打包编译至指定目录,即快速制作发行版
#----------------------------------------------

# 后端项目目录
backend_folder=$(dirname "`pwd`")
# 获取当前路径的上一级
project_path=$(dirname ${backend_folder})
# 前端项目目录
frontend_folder="${project_path}/niu-video-frontend"

docker_path="/opt/env"

# 构建后的二进制执行文件名
exec_file_name="niu-video"




function echo_red() {
    echo -e "\033[1;31m$1\033[0m"
}

function echo_green() {
    echo -e "\033[1;32m$1\033[0m"
}

function echo_yellow() {
    echo -e "\033[1;33m$1\033[0m"
}

function buildFrontend() {
    cd ${frontend_folder}
    echo_yellow "-------------------打包前端开始-------------------"
    # 检查是否已安装Vite
    if ! command -v vite &> /dev/null; then
      # 未安装Vite，执行npm安装命令
      npm i vite -g
    else
      echo "Vite已经安装，无需执行安装命令。"
    fi

    if [ -d "node_modules" ]; then
      echo "所有的包都已经安装过了"
    else
      echo "执行npm i"
      npm i
    fi
    rm -rf ./dict && npm run build

    if [ -d ${backend_folder}/deploy/nginx/static ] ; then
        echo_green "${backend_folder}/deploy/nginx/static文件夹存在,删除文件夹"
        sudo rm -rf ${backend_folder}/deploy/nginx/static
    fi
    mkdir ${backend_folder}/deploy/nginx/static
    cp -r ./dist/* ${backend_folder}/deploy/nginx/static/
    echo_yellow ">>>>>>>>>>>>>>>>>>>打包前端结束<<<<<<<<<<<<<<<<<<<<\n"
}

function buildDocker() {
    cd ${backend_folder}
#    cp config.yml.example config.yml
    echo_yellow "-------------------构建docker镜像开始-------------------"
    imageVersion=$1
    imageName="niu-video/niu-video-backend:${imageVersion}"
    docker build -t "${imageName}" -f ./deploy/Dockerfile .
    echo_green "docker镜像构建完成->[${imageName}]"
    echo_yellow "-------------------构建docker镜像结束-------------------"
}

function copy() {
    # 打包产物的输出目录
    echo_yellow "--------------复制数据卷映射文件开始--------------"

    if [ ! -d ${docker_path} ] ; then
        echo_green "${docker_path}文件夹不存在,创建文件夹"
        sudo mkdir ${docker_path}
    fi

     cp -rf ${backend_folder}/deploy/mysql ${docker_path}/mysql
     echo_green "${docker_path}/mysql文件夹复制成功"
     rm -rf ${docker_path}/nginx
     cp -rf ${backend_folder}/deploy/nginx ${docker_path}/nginx
     echo_green "${docker_path}/nginx文件夹复制成功"
     cp -rf ${backend_folder}/deploy/redis ${docker_path}/redis
     echo_green "${docker_path}/redis文件夹复制成功"
     mkdir -p ${docker_path}/es/data && mkdir -p ${docker_path}/es/data
     chmod 777 ${docker_path}/es/**

     echo_green "${docker_path}/es文件夹复制成功"
     echo_yellow ">>>>>>>>>>>>>>>>>>>复制完成<<<<<<<<<<<<<<<<<<<<\n"
}


function runBuild() {
    toPath="."
    imageVersion="latest"

    buildFrontend
    copy
    read -p "请输入docker镜像版本号[默认latest]: " imageVersion
    if [ "${imageVersion}" == "" ] ; then
        imageVersion="latest"
    fi

    buildDocker ${imageVersion}
}

runBuild
